<template>
    <a-modal
        title="端口设置"
        :visible="visible"
        width="820px"
        @ok="handleOk"
        @cancel="handleCancel"
    >
        <a-spin :spinning="loadingDeviceType" tip="正在加载设备类型数据...">
            <a-form-model
                ref="portForm"
                :model="form"
                :rules="rules"
                :label-col="{ span: 7 }"
                :wrapper-col="{ span: 17 }"
            >
                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-form-model-item label="端口名称" prop="name" required>
                            <a-input v-model="form.name" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item label="设备类型" prop="proto_type" required>
                            <a-select v-model="form.proto_type">
                                <a-select-option
                                    v-for="opt in deviceTypeOptions"
                                    :key="opt.value"
                                    :value="opt.value"
                                >
                                    {{ opt.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-model-item label="等待应答超时">
                            <a-input v-model="form.extra.resp_time_out_ms" addon-after="ms" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item label="采集周期">
                            <a-input v-model="form.extra.sample_interval_s" addon-after="s" />
                        </a-form-model-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-model-item label="帧间隔时间">
                            <a-input
                                v-model="form.extra.frame_interval_ms"
                                addon-after="ms"
                            />
                        </a-form-model-item>
                    </a-col>
                </a-row>

                <a-tabs
                    v-model="form.activeTab"
                    class="port-type-tabs"
                    @change="handleTabChange"
                >
                    <a-tab-pane
                        key="serial"
                        tab="串口"
                        :disabled="isTabDisabled && allowedTab !== 'serial'"
                    >
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-model-item label="串口号">
                                    <a-select v-model="form.extra.port">
                                        <a-select-option
                                            v-for="port in comPortOptions"
                                            :key="port"
                                            :value="port"
                                        >
                                            {{ port }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item label="波特率">
                                    <a-select v-model="form.extra.baud">
                                        <a-select-option
                                            v-for="baud in baudRateOptions"
                                            :key="baud"
                                            :value="baud"
                                        >
                                            {{ baud }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item label="校验位">
                                    <a-select v-model="form.extra.parity">
                                        <a-select-option value="None">None</a-select-option>
                                        <a-select-option value="Odd">Odd</a-select-option>
                                        <a-select-option value="Even">Even</a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item label="数据位">
                                    <a-select v-model="form.extra.bits">
                                        <a-select-option value="8">8</a-select-option>
                                        <a-select-option value="7">7</a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item label="停止位">
                                    <a-select v-model="form.extra.stop">
                                        <a-select-option value="1">1</a-select-option>
                                        <a-select-option value="2">2</a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>

                            <template v-if="showCustomClientSettings">
                                <a-col :span="12">
                                    <a-form-model-item
                                        label="远程IP地址"
                                        :label-col="{ span: 7 }"
                                        :wrapper-col="{ span: 17 }"
                                    >
                                        <a-input 
                                            v-model="form.extra.remote.address"
                                            :disabled="isRemoteAddressDisabled"
                                            :placeholder="isRemoteAddressDisabled ? '该设备类型不支持远程地址' : '请输入远程IP地址'"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-model-item
                                        label="端口号"
                                        :label-col="{ span: 7 }"
                                        :wrapper-col="{ span: 17 }"
                                    >
                                        <a-input v-model="form.extra.remote.port" />
                                    </a-form-model-item>
                                </a-col>
                            </template>
                            <template v-else>
                                <a-col :span="12">
                                    <a-form-model-item
                                        label="桥接的端口号"
                                        :label-col="{ span: 7 }"
                                        :wrapper-col="{ span: 17 }"
                                    >
                                        <a-row type="flex" align="middle">
                                            <a-col :span="12">
                                                <a-select
                                                    v-model="form.extra.bridgePort"
                                                    :disabled="!isDeviceTypeEnabled"
                                                    placeholder="请选择端口号"
                                                >
                                                    <a-select-option
                                                        v-for="option in bridgePortOptions"
                                                        :key="option"
                                                        :value="option"
                                                    >
                                                        {{ option }}
                                                    </a-select-option>
                                                </a-select>
                                            </a-col>
                                            <a-col :span="12">
                                                <a-checkbox
                                                    v-model="form.extra.remote.enableBridge"
                                                    :disabled="!isDeviceTypeEnabled"
                                                    style="padding-left: 8px;"
                                                >
                                                    启用桥接
                                                </a-checkbox>
                                            </a-col>
                                        </a-row>
                                    </a-form-model-item>
                                </a-col>
                            </template>
                        </a-row>

                        <div v-if="form.proto_type === '3020'">
                            <div class="custom-settings-panel">
                                <a-form-model
                                    :model="form.extra.remote"
                                    :label-col="{ span: 4 }"
                                    :wrapper-col="{ span: 20 }"
                                >
                                    <h4>自定义Client透传报文设置</h4>
                                    <a-form-model-item label="心跳时间">
                                        <a-input
                                            v-model="
                                                form.extra.remote.heartbeatInterval
                                            "
                                            addon-after="秒"
                                            style="width: 150px;"
                                        />
                                    </a-form-model-item>

                                    <div class="setting-group">
                                        <h5>设置心跳报文</h5>
                                        <p class="description">
                                            说明：请转换为16进制字符串输入(最长50个字符)
                                        </p>
                                        <a-form-model-item label="心跳报文">
                                            <a-textarea
                                                v-model="
                                                    form.extra.remote.heartbeatMessage
                                                "
                                                :rows="2"
                                            />
                                        </a-form-model-item>
                                    </div>

                                    <div class="setting-group">
                                        <h5>设置报文头尾</h5>
                                        <p class="description">
                                            说明：请转换为16进制字符串输入(报头或报尾最长4个字符)
                                        </p>
                                        <a-row :gutter="16">
                                            <a-col :span="12">
                                                <a-form-model-item
                                                    label="报文头"
                                                    :label-col="{ span: 8 }"
                                                    :wrapper-col="{ span: 16 }"
                                                >
                                                    <a-input
                                                        v-model="
                                                            form.extra.remote.messageHeader
                                                        "
                                                    />
                                                </a-form-model-item>
                                            </a-col>
                                            <a-col :span="12">
                                                <a-form-model-item
                                                    label="报文尾"
                                                    :label-col="{ span: 8 }"
                                                    :wrapper-col="{ span: 16 }"
                                                >
                                                    <a-input
                                                        v-model="
                                                            form.extra.remote.messageTail
                                                        "
                                                    />
                                                </a-form-model-item>
                                            </a-col>
                                        </a-row>
                                    </div>
                                </a-form-model>
                            </div>
                        </div>
                    </a-tab-pane>
                    <a-tab-pane
                        key="ethernet"
                        tab="以太网"
                        :disabled="isTabDisabled && allowedTab !== 'ethernet'"
                        force-render
                    >
                        <!-- OPC UA设备 -->
                        <template v-if="form.proto_type === '3112'">
                            <a-row :gutter="24">
                                <a-col :span="12">
                                    <a-form-model-item label="OPC UA地址">
                                        <a-input v-model="form.extra.opc.endpointURL" placeholder="请输入OPC UA地址" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-model-item label="设备端口号">
                                        <a-input 
                                            disabled
                                            placeholder="502"
                                        />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            
                            <!-- OPC登录模式选择 -->
                            <a-row>
                                <a-col :span="24">
                                    <a-form-model-item 
                                        label="登录模式"
                                    >
                                        <a-radio-group 
                                            v-model="form.extra.opc.loginType"
                                            class="opc-login-type-group"
                                        >
                                            <a-radio :value="'anonymous'">匿名登录</a-radio>
                                            <a-radio :value="'username'">用户名登录</a-radio>
                                            <a-radio :value="'certificate'">证书登录</a-radio>
                                        </a-radio-group>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>

                            <!-- 用户名登录表单 -->
                            <a-row v-if="form.extra.opc.loginType === 'username'" :gutter="24">
                                <a-col :span="12">
                                    <a-form-model-item label="用户名">
                                        <a-input v-model="form.extra.opc.usrName" placeholder="请输入用户名" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-model-item label="密码">
                                        <a-input-password v-model="form.extra.opc.password" placeholder="请输入密码" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>

                            <!-- 证书登录表单 -->
                            <a-row v-if="form.extra.opc.loginType === 'certificate'" :gutter="24">
                                <a-col :span="12">
                                    <a-form-model-item label="证书">
                                        <div class="file-input-group">
                                            <a-input v-model="form.extra.opc.certificate" placeholder="请选择证书文件" />
                                            <a-button size="small" @click="handleSelectCertificate">选择</a-button>
                                        </div>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-model-item label="密钥">
                                        <div class="file-input-group">
                                            <a-input v-model="form.extra.opc.key" placeholder="请选择密钥文件" />
                                            <a-button size="small" @click="handleSelectKey">选择</a-button>
                                        </div>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </template>
                        
                        <!-- 其他设备 -->
                        <template v-else>
                            <a-row :gutter="24">
                                <a-col :span="12">
                                    <a-form-model-item label="设备IP地址">
                                        <a-input v-model="form.extra.ip_addr" placeholder="请输入设备IP地址" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-model-item label="端口号">
                                        <a-input v-model="form.extra.ip_port" placeholder="请输入端口号" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </template>
                    </a-tab-pane>
                    <a-tab-pane
                        key="internal"
                        tab="内部"
                        :disabled="isTabDisabled && allowedTab !== 'internal'"
                        force-render
                    >
                        <p>内部设置内容...</p>
                    </a-tab-pane>
                </a-tabs>
            </a-form-model>
        </a-spin>
    </a-modal>
</template>

<script>
import { mapGetters } from 'vuex'
import tabManager from '@/api/tab-manager'
import { GATEWAY_CONFIGS } from '@/config/gateway-config'
import { openFileDialog } from '@/api/TabAxios/base'
import _ from 'lodash'

export default {
    name: 'PortSettingsModal',
    props: {
        visible: { type: Boolean, required: true },
        portData: { type: Object, default: () => ({}) }
    },
    data() {
        const initialFormState = {
            id: -1,
            group_device_id: -1,
            name: 'port',
            proto_type: '',
            activeTab: 'serial', // 默认选中串口tab
            extra: {
                enable: 1,
                type: '',
                device_type: '',
                port: 'COM1',
                baud: '9600',
                parity: 'None',
                bits: '8',
                stop: '1',
                resp_time_out_ms: '3000',
                sample_interval_s: '30',
                frame_interval_ms: '300',
                ip_addr: '127.0.0.1',
                ip_port: '8080',
                bridgePort: '',
                convert: {
                    com: -1,
                    port: 8080,
                    enable: true
                },
                opc: {
                    loginType: 'anonymous',
                    endpointURL: '',
                    usrName: '',
                    password: '',
                    certificate: '',
                    key: ''
                },
                remote: {
                    address: '',
                    port: '',
                    reportPackage: '',
                    reportHead: '',
                    reportTail: '',
                    heartTime: ''
                }
            }
        }

        return {
            form: _.cloneDeep(initialFormState),
            rules: {
                name: [{ required: true, message: '请输入端口名称', trigger: 'blur' }],
                proto_type: [
                    { required: true, message: '请选择设备类型', trigger: 'change' }
                ]
            },
            initialFormState,
            deviceTypeData: null, // 存储设备类型数据
            loadingDeviceType: false, // 加载状态
            deviceTypeOptions: [], // 动态设备类型选项
            // 新增：缓存不同模式的设备类型数据
            deviceTypeCache: {
                serialport: null,
                ethernet: null,
                internal: null
            },
            comPortOptions: [
                'COM1',
                'COM2',
                'COM3',
                'COM4',
                'COM5',
                'COM6',
                'COM7',
                'COM8',
                'COM9'
            ],
            baudRateOptions: ['9600', '19200', '38400', '57600', '115200'],
            // 桥接端口号选项，由后端生成
            bridgePortOptions: []
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo']),

        // 获取当前设备的更新模式
        currentDeviceUpdateMode() {
            if (!this.selectedDeviceInfo) {
                return 'ethernet' // 默认为网络模式
            }

            // 如果直接有updateMode属性，使用它
            if (this.selectedDeviceInfo.updateMode) {
                return this.selectedDeviceInfo.updateMode
            }

            // 根据设备类型获取updateMode
            const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
            const config = GATEWAY_CONFIGS[deviceType]
            
            if (config && config.hardwareInfo && config.hardwareInfo.updateMode) {
                return config.hardwareInfo.updateMode
            }

            return 'ethernet' // 默认为网络模式
        },
        allowedTab() {
            if (this.currentDeviceUpdateMode === 'serialport') return 'serial'
            if (this.currentDeviceUpdateMode === 'ethernet') return 'ethernet'
            if (this.currentDeviceUpdateMode === 'internal') return 'internal'
            return 'serial'
        },
        
        // 判断tab是否应该被禁用
        isTabDisabled() {
            if (this.currentDeviceUpdateMode === 'ethernet') {
                return false // ethernet模式下不禁用任何tab
            }
            if (this.currentDeviceUpdateMode === 'serialport') {
                return true // serial模式下禁用其他tab
            }
            return false
        },
        isDeviceTypeEnabled() {
            return this.form.proto_type === '3014' || this.form.proto_type === '3001'
        },
        
        // 判断是否显示自定义Client透传报文设置
        showCustomClientSettings() {
            const supportedTypes = ['3018', '3019', '3020', '3021', '3022']
            return supportedTypes.includes(this.form.proto_type)
        },
        
        // 判断远程地址是否禁用
        isRemoteAddressDisabled() {
            return ['3019', '3021'].includes(this.form.proto_type)
        }
    },
    watch: {
        portData: {
            handler(newData) {
                console.log('🔍 [PortSettingsModal] 端口数据更新:', newData)
                // 使用深度合并：以模板为基础，用后端数据覆盖对应字段
                if (newData && Object.keys(newData).length) {
                    // 1. 克隆完整的模板结构（确保所有字段都有默认值）
                    const template = _.cloneDeep(this.initialFormState)
                    // 2. 深度合并后端数据（只覆盖后端返回的字段，其他保持默认值）
                    this.form = _.merge(template, _.cloneDeep(newData))
                    console.log('✅ [PortSettingsModal] 数据合并完成:', {
                        模板字段: Object.keys(template.extra),
                        后端数据: newData,
                        合并结果: this.form
                    })
                    
                    // 数据合并完成后，更新表单选项（但不要覆盖已有的activeTab）
                    this.updateFormOptions()
                } else {
                    this.form = _.cloneDeep(this.initialFormState)
                    // 兜底，确保默认选中匿名登录
                    this.form.extra.opc.loginType = 'anonymous'
                    // 对于空数据，使用默认的updateFormOptions
                    this.updateFormOptions()
                }
                
                // 强制触发响应式更新
                this.$forceUpdate()
            },
            immediate: true,
            deep: true
        },
        visible: {
            handler(newVisible) {
                if (newVisible) {
                    console.log('🔍 [PortSettingsModal] 弹窗打开，开始预加载所有设备类型数据')
                    // 使用预加载方法，同时加载串口和网口数据
                    this.preloadAllDeviceTypeData()
                    this.loadBridgePortOptions()
                }
            },
            immediate: false
        },
        // 监听选中设备变化，清理缓存确保数据一致性
        selectedDeviceInfo: {
            handler(newDevice, oldDevice) {
                // 如果设备发生变化，清理缓存
                if (newDevice && oldDevice && newDevice.id !== oldDevice.id) {
                    console.log('🔄 [PortSettingsModal] 设备变化，清理设备类型缓存')
                    this.clearDeviceTypeCache()
                }
            },
            immediate: false
        }
    },
    methods: {
        async loadDeviceTypeData() {
            try {
                this.loadingDeviceType = true

                // 检查是否有选中的设备信息
                if (!this.selectedDeviceInfo) {
                    console.warn('🚨 [PortSettingsModal] 没有选中的设备信息')
                    this.$message.warning('请先选择一个设备')
                    return
                }

                // 获取设备的更新模式
                const updateMode = this.currentDeviceUpdateMode

                console.log('🔍 [PortSettingsModal] 正在获取设备类型数据:', {
                    updateMode: updateMode,
                    deviceInfo: this.selectedDeviceInfo,
                    gatewayType: this.selectedDeviceInfo.gatewayType
                })

                // 优先从缓存加载
                if (this.deviceTypeCache[updateMode]) {
                    this.deviceTypeOptions = [...this.deviceTypeCache[updateMode]] // 使用浅拷贝避免引用问题
                    console.log('✅ [PortSettingsModal] 从缓存加载设备类型数据')
                } else {
                    // 调用接口获取设备类型数据，传递更新模式
                    const response = await tabManager.monitor.getPortLoadDeviceType(
                        updateMode
                    )

                    console.log('✅ [PortSettingsModal] 设备类型数据获取成功:', response)

                    // 根据接口返回的数据结构处理
                    if (response && response.code === 0) {
                        let options = response.data
                        if (typeof options === 'string') {
                            try {
                                options = JSON.parse(options)
                            } catch (e) {
                                options = []
                            }
                        }

                        // 使用统一的数据处理方法，确保去重
                        this.deviceTypeOptions = this.processDeviceTypeData(options)

                        // 缓存数据
                        this.deviceTypeCache[updateMode] = [...this.deviceTypeOptions] // 使用浅拷贝存储

                        if (this.deviceTypeOptions.length > 0) {
                            // 期望的协议类型（优先取编辑模式下的原值，否则使用当前表单中的值）
                            const desired = (this.portData && this.portData.proto_type)
                                ? this.portData.proto_type
                                : this.form.proto_type
                            const exists = this.deviceTypeOptions.some(opt => opt.value === desired)

                            // 如果期望值不存在（例如被过滤掉了3112），回退到第一个可用项
                            this.form.proto_type = exists ? desired : this.deviceTypeOptions[0].value
                        } else {
                            // 没有可用项时清空
                            this.form.proto_type = ''
                        }
                        this.updateFormOptions()
                        console.log(
                            '🔍 [PortSettingsModal] 设备类型选项:',
                            this.deviceTypeOptions
                        )
                    } else {
                        this.deviceTypeOptions = []
                        this.form.proto_type = ''
                        this.$message.warning(response?.message || '获取设备类型数据失败')
                    }
                }
            } catch (error) {
                console.error('❌ [PortSettingsModal] 获取设备类型数据失败:', error)
                this.$message.error('获取设备类型数据失败')
            } finally {
                this.loadingDeviceType = false
            }
        },

        // 统一的设备类型数据处理方法，确保数据去重和缓存一致性
        processDeviceTypeData(rawOptions) {
            if (!Array.isArray(rawOptions)) {
                return []
            }

            // 处理原始数据并去重
            const processedOptions = rawOptions.map(opt => {
                const [value] = opt.split(':')
                return { value, label: opt }
            })

            // 根据value去重，确保没有重复项
            const uniqueOptions = processedOptions.filter((option, index, self) => 
                index === self.findIndex(item => item.value === option.value)
            )

            // 非WG60设备不允许使用 3112，直接过滤掉
            const isWG60 = this.selectedDeviceInfo && this.selectedDeviceInfo.gatewayType === 'WG60'
            if (!isWG60) {
                return uniqueOptions.filter(opt => opt.value !== '3112')
            }

            return uniqueOptions
        },

        // 清理设备类型缓存
        clearDeviceTypeCache() {
            console.log('🧹 [PortSettingsModal] 清理设备类型缓存')
            this.deviceTypeCache = {
                serialport: null,
                ethernet: null,
                internal: null
            }
        },

        // 新增：预加载所有模式的设备类型数据
        async preloadAllDeviceTypeData() {
            try {
                console.log('🔍 [PortSettingsModal] 开始预加载所有设备类型数据')
                this.loadingDeviceType = true

                // 检查是否有选中的设备信息
                if (!this.selectedDeviceInfo) {
                    console.warn('🚨 [PortSettingsModal] 没有选中的设备信息')
                    return
                }

                // 需要预加载的模式
                const modesToPreload = ['serialport', 'ethernet']
                
                // 并行加载两种模式的数据
                const loadPromises = modesToPreload.map(async mode => {
                    if (this.deviceTypeCache[mode]) {
                        console.log(`✅ [PortSettingsModal] ${mode}模式数据已缓存，跳过`)
                        return
                    }

                    try {
                        console.log(`🔍 [PortSettingsModal] 预加载${mode}模式设备类型数据`)
                        const response = await tabManager.monitor.getPortLoadDeviceType(mode)
                        
                        if (response && response.code === 0) {
                            let options = response.data
                            if (typeof options === 'string') {
                                try {
                                    options = JSON.parse(options)
                                } catch (e) {
                                    options = []
                                }
                            }

                            // 使用统一的数据处理方法，确保去重
                            const deviceTypeOptions = this.processDeviceTypeData(options)

                            // 缓存数据
                            this.deviceTypeCache[mode] = deviceTypeOptions
                            console.log(`✅ [PortSettingsModal] ${mode}模式设备类型数据预加载完成:`, deviceTypeOptions)
                        } else {
                            console.warn(`⚠️ [PortSettingsModal] ${mode}模式设备类型数据获取失败:`, response?.message)
                        }
                    } catch (error) {
                        console.error(`❌ [PortSettingsModal] 预加载${mode}模式设备类型数据失败:`, error)
                    }
                })

                // 等待所有预加载完成
                await Promise.all(loadPromises)
                
                // 设置当前模式的设备类型选项
                const currentMode = this.currentDeviceUpdateMode
                if (this.deviceTypeCache[currentMode]) {
                    this.deviceTypeOptions = [...this.deviceTypeCache[currentMode]] // 使用浅拷贝避免引用问题
                    
                    if (this.deviceTypeOptions.length > 0) {
                        // 期望的协议类型（优先取编辑模式下的原值，否则使用当前表单中的值）
                        const desired = (this.portData && this.portData.proto_type)
                            ? this.portData.proto_type
                            : this.form.proto_type
                        const exists = this.deviceTypeOptions.some(opt => opt.value === desired)

                        // 如果期望值不存在（例如被过滤掉了3112），回退到第一个可用项
                        this.form.proto_type = exists ? desired : this.deviceTypeOptions[0].value
                    } else {
                        // 没有可用项时清空
                        this.form.proto_type = ''
                    }
                    this.updateFormOptions()
                }

                console.log('✅ [PortSettingsModal] 所有设备类型数据预加载完成')
            } catch (error) {
                console.error('❌ [PortSettingsModal] 预加载设备类型数据失败:', error)
                this.$message.error('预加载设备类型数据失败')
            } finally {
                this.loadingDeviceType = false
            }
        },

        updateFormOptions() {
            console.log('🔄 [PortSettingsModal] 根据设备类型数据更新表单选项')
            console.log(
                '📋 [PortSettingsModal] 当前设备更新模式:',
                this.currentDeviceUpdateMode
            )

            // 映射更新模式到对应的tab key
            const tabMapping = {
                serialport: 'serial',
                ethernet: 'ethernet',
                internal: 'internal'
            }

            const targetTab = tabMapping[this.currentDeviceUpdateMode] || 'serial'
            console.log('🎯 [PortSettingsModal] 目标tab:', targetTab)

            // 只有在没有端口数据或端口数据中没有指定activeTab时，才使用默认的targetTab
            if (!this.portData || !this.portData.activeTab) {
                console.log('🔄 [PortSettingsModal] 使用默认tab:', targetTab)
                this.form.activeTab = targetTab
            } else {
                console.log('🔄 [PortSettingsModal] 保持端口数据中的activeTab:', this.portData.activeTab)
                // 保持端口数据中指定的activeTab
                this.form.activeTab = this.portData.activeTab
            }
        },

        handleTabChange(tabKey) {
            console.log('🔄 [PortSettingsModal] Tab切换:', { tabKey, currentMode: this.currentDeviceUpdateMode })
            
            // 如果当前模式是ethernet，则允许自由切换，且需要切换对应的设备类型数据
            if (this.currentDeviceUpdateMode === 'ethernet') {
                // 根据tab切换对应的设备类型数据
                const tabToModeMapping = {
                    'serial': 'serialport',
                    'ethernet': 'ethernet',
                    'internal': 'internal'
                }
                
                const targetMode = tabToModeMapping[tabKey] || 'ethernet'
                
                // 如果缓存中有数据，直接使用缓存
                if (this.deviceTypeCache[targetMode]) {
                    this.deviceTypeOptions = [...this.deviceTypeCache[targetMode]] // 使用浅拷贝避免引用问题
                    console.log(`✅ [PortSettingsModal] 从缓存加载${targetMode}模式设备类型数据`)
                    
                    // 更新设备类型选择
                    if (this.deviceTypeOptions.length > 0) {
                        // 如果当前选择的设备类型在新模式下不存在，则选择第一个可用项
                        const exists = this.deviceTypeOptions.some(opt => opt.value === this.form.proto_type)
                        if (!exists) {
                            this.form.proto_type = this.deviceTypeOptions[0].value
                        }
                    }
                } else {
                    // 如果缓存中没有数据，异步加载
                    this.loadDeviceTypeDataByMode(targetMode)
                }
                return
            }
            
            // serial模式下限制切换
            if (this.currentDeviceUpdateMode === 'serialport' && tabKey !== this.allowedTab) {
                this.$message.warning(
                    '当前设备类型只允许操作"' + this.getTabLabel(this.allowedTab) + '"'
                )
                this.form.activeTab = this.allowedTab
            }
        },

        // 新增：根据指定模式加载设备类型数据
        async loadDeviceTypeDataByMode(mode) {
            try {
                console.log(`🔍 [PortSettingsModal] 加载${mode}模式设备类型数据`)
                this.loadingDeviceType = true

                // 检查缓存，如果已有数据则直接使用
                if (this.deviceTypeCache[mode]) {
                    this.deviceTypeOptions = [...this.deviceTypeCache[mode]]
                    console.log(`✅ [PortSettingsModal] 从缓存加载${mode}模式设备类型数据`)
                    
                    // 更新设备类型选择
                    if (this.deviceTypeOptions.length > 0) {
                        const exists = this.deviceTypeOptions.some(opt => opt.value === this.form.proto_type)
                        if (!exists) {
                            this.form.proto_type = this.deviceTypeOptions[0].value
                        }
                    }
                    return
                }

                const response = await tabManager.monitor.getPortLoadDeviceType(mode)
                
                if (response && response.code === 0) {
                    let options = response.data
                    if (typeof options === 'string') {
                        try {
                            options = JSON.parse(options)
                        } catch (e) {
                            options = []
                        }
                    }

                    // 使用统一的数据处理方法，确保去重
                    const deviceTypeOptions = this.processDeviceTypeData(options)

                    // 缓存数据
                    this.deviceTypeCache[mode] = [...deviceTypeOptions] // 使用浅拷贝存储
                    this.deviceTypeOptions = [...deviceTypeOptions] // 使用浅拷贝避免引用问题
                    
                    // 更新设备类型选择
                    if (this.deviceTypeOptions.length > 0) {
                        const exists = this.deviceTypeOptions.some(opt => opt.value === this.form.proto_type)
                        if (!exists) {
                            this.form.proto_type = this.deviceTypeOptions[0].value
                        }
                    }
                    
                    console.log(`✅ [PortSettingsModal] ${mode}模式设备类型数据加载完成:`, deviceTypeOptions)
                } else {
                    console.warn(`⚠️ [PortSettingsModal] ${mode}模式设备类型数据获取失败:`, response?.message)
                    this.$message.warning(response?.message || `获取${mode}模式设备类型数据失败`)
                }
            } catch (error) {
                console.error(`❌ [PortSettingsModal] 加载${mode}模式设备类型数据失败:`, error)
                this.$message.error(`加载${mode}模式设备类型数据失败`)
            } finally {
                this.loadingDeviceType = false
            }
        },
        getTabLabel(tabKey) {
            if (tabKey === 'serial') return '串口'
            if (tabKey === 'ethernet') return '以太网'
            if (tabKey === 'internal') return '内部'
            return tabKey
        },

        handleOk() {
            this.$refs.portForm.validate(valid => {
                if (valid) {
                    this.$emit('ok', this.form)
                }
            })
        },
        handleCancel() {
            this.$emit('cancel')
        },
        // 加载桥接端口号选项（由后端生成）
        // 选择证书文件
        async handleSelectCertificate() {
            try {
                const result = await openFileDialog({
                    title: '选择证书文件',
                    filter: '证书文件 (*.crt;*.pem;*.cer)|*.crt;*.pem;*.cer|所有文件 (*.*)|*.*'
                })
                if (result && result.filePath) {
                    this.form.extra.opc.certificate = result.filePath
                }
            } catch (error) {
                console.error('❌ [PortSettingsModal] 选择证书文件失败:', error)
                this.$message.error('选择证书文件失败')
            }
        },

        // 选择密钥文件
        async handleSelectKey() {
            try {
                const result = await openFileDialog({
                    title: '选择密钥文件',
                    filter: '密钥文件 (*.key;*.pem)|*.key;*.pem|所有文件 (*.*)|*.*'
                })
                if (result && result.filePath) {
                    this.form.extra.opc.key = result.filePath
                }
            } catch (error) {
                console.error('❌ [PortSettingsModal] 选择密钥文件失败:', error)
                this.$message.error('选择密钥文件失败')
            }
        },

        async loadBridgePortOptions() {
            try {
                console.log('🔍 [PortSettingsModal] 开始加载桥接端口号选项')
                // 这里可以调用后端接口获取端口号选项
                const response = await tabManager.monitor.getBridgePortOptions()
                if (response && response.code === 0) {
                    this.bridgePortOptions = JSON.parse(response.data)
                    // 如果更新的数据有bridgePort，则使用更新的数据
                    if (this.portData && this.portData.extra && this.portData.extra.bridgePort) {
                        this.form.extra.bridgePort = this.portData.extra.bridgePort
                    } else {
                        this.form.extra.bridgePort = this.bridgePortOptions[0]
                    }
                }
                console.log('✅ [PortSettingsModal] 桥接端口号选项加载完成:', this.bridgePortOptions)
            } catch (error) {
                console.error('❌ [PortSettingsModal] 加载桥接端口号选项失败:', error)
                this.$message.error('加载端口号选项失败')
            }
        }
    }
}
</script>

<style scoped>
.port-type-tabs {
    border: 1px solid #d9d9d9;
    padding: 16px;
    border-radius: 4px;
}
.custom-settings-panel {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 24px;
    margin-top: 0;
    background: #fafafa;
}
.custom-settings-panel h4 {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 2px;
}
.setting-group h5 {
    font-size: 14px;
    font-weight: 500;
    margin-top: 16px;
    margin-bottom: 4px;
}
.setting-group .description {
    color: #f5222d;
    margin-bottom: 8px;
    font-size: 12px;
}

/* 文件选择输入框组 */
.file-input-group {
    display: flex;
    align-items: center;
    gap: 8px;
}
.file-input-group .ant-input {
    flex: 1;
}
.file-input-group .ant-btn {
    flex-shrink: 0;
}

/* OPC登录模式样式 */
.opc-login-type-group {
    display: inline-flex;
    flex-direction: row;
    align-items: center;
    gap: 24px;
}
.opc-login-type-group .ant-radio-wrapper {
    margin: 0;
    padding: 0;
}
</style> 